package com.resou.reader.reader.view;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.androidquery.callback.AQuery2;
import com.androidquery.callback.AjaxStatus;
import com.androidquery.callback.BitmapAjaxCallback;
import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdDislike;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTImage;
import com.bytedance.sdk.openadsdk.TTNativeAd;
import com.qq.e.ads.cfg.VideoOption;
import com.qq.e.ads.contentad.ContentAD;
import com.qq.e.ads.contentad.ContentAdData;
import com.qq.e.ads.nativ.ADSize;
import com.qq.e.ads.nativ.NativeADEventListener;
import com.qq.e.ads.nativ.NativeADMediaListener;
import com.qq.e.ads.nativ.NativeADUnifiedListener;
import com.qq.e.ads.nativ.NativeExpressAD;
import com.qq.e.ads.nativ.NativeExpressADView;
import com.qq.e.ads.nativ.NativeUnifiedAD;
import com.qq.e.ads.nativ.NativeUnifiedADData;
import com.qq.e.ads.nativ.widget.NativeAdContainer;
import com.qq.e.comm.constants.AdPatternType;
import com.qq.e.comm.pi.AdData;
import com.qq.e.comm.util.AdError;
import com.resou.reader.R;
import com.resou.reader.ReSouApplication;
import com.resou.reader.advert.TTAdManagerHolder;
import com.resou.reader.reader.OnAdViewLoadListener;
import com.resou.reader.utils.Constants;
import com.resou.reader.utils.DateUtil;
import com.resou.reader.utils.PreferenceUtil;
import com.resou.reader.utils.TextUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;

import static com.qq.e.ads.nativ.ADSize.AUTO_HEIGHT;

/**
 * 单页广告
 */

public class NativeTTAdView extends FrameLayout implements TTAdNative.NativeAdListener, NativeExpressAD.NativeExpressADListener {
    private static final String TAG = "Reader_AD";
    /**
     * 穿山甲广告接入
     */
    private TTAdNative mTTAdNative;
    private TTAdDislike ttAdDislike;
    private Activity mContext;
    private AQuery2 mAQuery = new AQuery2(this);
    private FrameLayout mRootView;
    private RelativeLayout rlBg;
    private LinearLayout largeView;
    TextView mCreativeButton;
    TextView mTitle;
    TextView mDescription;
    TextView tvShare;
    ImageView mLargeImage;
    ImageView ivLogo;
    RelativeLayout rlClear_Ad_tv;
    public int touchAdHeight;
    private OnAdViewLoadListener listener;
    List<TTNativeAd> list;
    boolean dateShareFlag = true;
    boolean clickable = true;

    Random random = new Random();
    /**
     * 腾讯信息流广告接入
     */
    boolean isCSJ = false;
    private NativeExpressAD nativeExpressAD;
    private NativeExpressADView nativeExpressADView;
    private FrameLayout flTXAd;

    public NativeTTAdView(Context context) {
        super(context);
        setContentView(context);
    }

    public NativeTTAdView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setContentView(context);
    }

    public NativeTTAdView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setContentView(context);
    }

    private void setContentView(final Context context) {
        Log.i(TAG, "setContentView: ");
        mContext = (Activity) context;
        LayoutInflater.from(this.mContext).inflate(R.layout.view_single_tt_advert, this);
        mRootView = findViewById(R.id.native_insert_ad_root);
        largeView = findViewById(R.id.largeView);
        flTXAd = findViewById(R.id.flTXAd);
        rlBg = findViewById(R.id.rlBg);
        rlClear_Ad_tv = findViewById(R.id.rlClear_Ad_tv);
        tvShare = findViewById(R.id.tvShare);
        TextUtils.setUnderLineSpan(tvShare, tvShare.getText().toString());
        if (PreferenceUtil.getInstance(mContext).getIsShare()) {
            tvShare.setVisibility(GONE);
        } else {
            tvShare.setVisibility(VISIBLE);
        }
        tvShare.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!clickable) {
                    return;
                }
                if (listener != null)
                    listener.onShare();
            }
        });
        rlClear_Ad_tv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!clickable) {
                    return;
                }
                if (listener != null)
                    listener.onMonthlyVip();
            }
        });
        mRootView.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });
        initData();
    }

    private void initData() {
        //step2:创建TTAdNative对象,用于调用广告请求接口
        mTTAdNative = TTAdManagerHolder.getInstance(mContext).createAdNative(mContext);
        //step3:可选，申请部分权限，如read_phone_state,防止获取不了imei时候，下载类广告没有填充的问题。
        TTAdManagerHolder.getInstance(mContext).requestPermissionIfNecessary(mContext);
        loadAdView();
    }


    public synchronized void loadAdView() {
        Log.i(TAG, "loadAdView: " + "拉去广告");
        int value = PreferenceUtil.getInstance(ReSouApplication.getRSApplication()).getAdProbabilityContent();
        isCSJ = (random.nextInt(100) + 1) <= value;
        if (isCSJ) {
            largeView.setVisibility(View.VISIBLE);
            flTXAd.setVisibility(View.GONE);
            rlBg.setVisibility(View.VISIBLE);
            Log.i(TAG, "穿山甲广告");
            //step4:创建广告请求参数AdSlot,注意其中的setNativeAdtype方法，具体参数含义参考文档
            @SuppressLint("WrongConstant") AdSlot adSlot = new AdSlot.Builder()
                    .setCodeId("912753619")
                    .setSupportDeepLink(true)
                    .setImageAcceptedSize(690, 388)
                    .setAdCount(1)
                    .setNativeAdType(AdSlot.TYPE_FEED)//请求原生广告时候，请务必调用该方法，设置参数为TYPE_BANNER或TYPE_INTERACTION_AD
                    .build();
            //step5:请求广告，对请求回调的广告作渲染处理
            mTTAdNative.loadNativeAd(adSlot, this);

        } else {
            Log.i(TAG, "腾讯广告");
            largeView.setVisibility(View.GONE);
            flTXAd.setVisibility(View.VISIBLE);
            rlBg.setVisibility(View.GONE);
            refreshAd();
        }
    }

    public void setListener(OnAdViewLoadListener listener) {
        this.listener = listener;
    }

    @Override
    public boolean onTouchEvent(MotionEvent e) {
        return false;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return !clickable;
    }

    @Override
    public void onError(int i, String s) {
        Log.e("8888", i + s);
    }

    @Override
    public void onNativeAdLoad(List<TTNativeAd> list) {
        this.list = list;
        if (list.get(0) == null) {
            return;
        }
        PreferenceUtil.getInstance(getContext()).saveAdData(list.get(0));
        showAd(list.get(0));
    }

    private void showAd(TTNativeAd ad) {

        if (ad.getImageMode() == TTAdConstant.IMAGE_MODE_LARGE_IMG) {
            getLargeAdView(ad);
            touchAdHeight = largeView.getMeasuredHeight();
        }
        ttAdDislike = ad.getDislikeDialog((Activity) mContext);
        if (ttAdDislike != null) {
            ttAdDislike.setDislikeInteractionCallback(new TTAdDislike.DislikeInteractionCallback() {
                @Override
                public void onSelected(int position, String value) {
                }

                @Override
                public void onCancel() {

                }
            });
        }

    }

    public void getLargeAdView(TTNativeAd ad) {
        if (ad == null) {
            return;
        }
        mDescription = findViewById(R.id.tv_large_ad_desc);
        mLargeImage = findViewById(R.id.iv_large_image);
        mCreativeButton = findViewById(R.id.btn_large_creative);
        ivLogo = findViewById(R.id.iv_large_logo);


        bindData(largeView, ad);
        if (ad.getImageList() != null && !ad.getImageList().isEmpty()) {
            TTImage image = ad.getImageList().get(0);
            if (image != null && image.isValid()) {
                Log.i(TAG, "getLargeAdView: " + image.getImageUrl() + "");
                mAQuery.id(mLargeImage).image(image.getImageUrl(), false, false, image.getWidth(), 0, new BitmapAjaxCallback() {
                    @Override
                    protected void callback(String url, ImageView iv, Bitmap bm, AjaxStatus status) {
                        super.callback(url, iv, bm, status);
                        if (status.getCode() == 200) {
                            if (listener != null) {
                                listener.onAdViewLoadListener();
                            }
                        }
                    }
                });
            }
        }
    }


    class ViewHolder {

    }

    private void bindData(View convertView, TTNativeAd ad) {
        //可以被点击的view, 也可以把convertView放进来意味item可被点击
        List<View> clickViewList = new ArrayList<>();
        clickViewList.add(convertView);
        //触发创意广告的view（点击下载或拨打电话）
        List<View> creativeViewList = new ArrayList<>();
        creativeViewList.add(mCreativeButton);
        //如果需要点击图文区域也能进行下载或者拨打电话动作，请将图文区域的view传入
        creativeViewList.add(convertView);
        //重要! 这个涉及到广告计费，必须正确调用。convertView必须使用ViewGroup。

        ad.registerViewForInteraction((ViewGroup) convertView, clickViewList, creativeViewList, new TTNativeAd.AdInteractionListener() {
            @Override
            public void onAdClicked(View view, TTNativeAd ad) {
//                if (ad != null) {
//                    ToastUtils.showSingleToast("广告" + ad.getTitle() + "被点击");
//                }
            }

            @Override
            public void onAdCreativeClick(View view, TTNativeAd ad) {
//                if (ad != null) {
//                    ToastUtils.showSingleToast("广告" + ad.getTitle() + "被创意按钮被点击");
//                }
            }

            @Override
            public void onAdShow(TTNativeAd ad) {
//                if (ad != null) {
//                    ToastUtils.showSingleToast("广告" + ad.getTitle() + "展示");
//                }
            }
        });
//        ad.getAdView().setClickable(clickable);
        mAQuery.id(ivLogo).image(ad.getAdLogo());
//        mTitle.setText(ad.getTitle()); //title为广告的简单信息提示
        mDescription.setText(ad.getDescription()); //description为广告的较长的说明
//        mSource.setText(ad.getSource() == null ? "广告来源" : ad.getSource());
//        TTImage icon = ad.getIcon();
//        if (icon != null && icon.isValid()) {
//            ImageOptions options = new ImageOptions();
//            mAQuery.id(mIcon).image(icon.getImageUrl(), options);
//
//        }
        switch (ad.getInteractionType()) {
            case TTAdConstant.INTERACTION_TYPE_DOWNLOAD:
                //如果初始化ttAdManager.createAdNative(getApplicationContext())没有传入activity 则需要在此传activity，否则影响使用Dislike逻辑
                if (mContext instanceof Activity) {
                    ad.setActivityForDownloadApp((Activity) mContext);
                }
                mCreativeButton.setVisibility(View.VISIBLE);
                mCreativeButton.setText("开始下载");
//                mStopButton.setVisibility(View.VISIBLE);
//                mRemoveButton.setVisibility(View.VISIBLE);
//                bindDownloadListener(adCreativeButton, adViewHolder, ad);
                //绑定下载状态控制器
//                bindDownLoadStatusController(adViewHolder, ad);
                break;
            case TTAdConstant.INTERACTION_TYPE_DIAL:
                mCreativeButton.setVisibility(View.VISIBLE);
                mCreativeButton.setText("立即拨打");
//                mStopButton.setVisibility(View.GONE);
//                mRemoveButton.setVisibility(View.GONE);
                break;
            case TTAdConstant.INTERACTION_TYPE_LANDING_PAGE:
            case TTAdConstant.INTERACTION_TYPE_BROWSER:
//                    adCreativeButton.setVisibility(View.GONE);
                mCreativeButton.setVisibility(View.VISIBLE);
                mCreativeButton.setText("查看详情");
//                mStopButton.setVisibility(View.GONE);
//                mRemoveButton.setVisibility(View.GONE);
                break;

        }
    }

    public int getTouchAdHeight() {
        return touchAdHeight;
    }


    public void setClickableOnclick(boolean isOnclick) {
        clickable = isOnclick;
//        mLargeImage.setClickable(isOnclick);
    }

    /**
     * 设置是否分享过
     *
     * @param dateShareFlag
     */
    public void setDateShareFlag(boolean dateShareFlag) {
        this.dateShareFlag = dateShareFlag;
        if (dateShareFlag) {
            tvShare.setVisibility(GONE);
        } else {
            tvShare.setVisibility(VISIBLE);
        }
    }

    /***
     *===========================腾讯广告接入================================
     */
    public void refreshAd() {
        /**
         *  如果选择支持视频的模版样式，请使用{@link Constants#NativeExpressSupportVideoPosID}
         */
        try {
            nativeExpressAD = new NativeExpressAD(mContext, getMyADSize(), Constants.APPID, "3080879100634407", this); // 这里的Context必须为Activity
            nativeExpressAD.loadAD(1);
        } catch (Exception e) {
            Log.i(TAG, "refreshAd: " + e.getMessage());
        }
    }

    /**
     * 获取广告数据
     *
     * @param nativeExpressADView
     * @return
     */
    private String getAdInfo(NativeExpressADView nativeExpressADView) {
        AdData adData = nativeExpressADView.getBoundData();
        if (adData != null) {
            StringBuilder infoBuilder = new StringBuilder();
            infoBuilder.append("title:").append(adData.getTitle()).append(",")
                    .append("desc:").append(adData.getDesc()).append(",")
                    .append("patternType:").append(adData.getAdPatternType());
            return infoBuilder.toString();
        }
        return null;
    }

    private ADSize getMyADSize() {
//        return new ADSize(ADSize.FULL_WIDTH, AUTO_HEIGHT);
        return new ADSize(ADSize.FULL_WIDTH, 220);
    }

    boolean isStart = false;

    @Override
    public void onADLoaded(List<NativeExpressADView> adList) {
        Log.i(TAG, "onADLoaded: " + adList.size());
        // 释放前一个展示的NativeExpressADView的资源
        if (nativeExpressADView != null && isStart) {
            nativeExpressADView.destroy();
            isStart = true;
        }
        if (flTXAd.getChildCount() > 0) {
            flTXAd.removeAllViews();
        }
        nativeExpressADView = adList.get(0);
        Log.i(TAG, "onADLoaded, video info: " + getAdInfo(nativeExpressADView));
        // 广告可见才会产生曝光，否则将无法产生收益。
        flTXAd.addView(nativeExpressADView);
        nativeExpressADView.render();
//        if (listener != null) {
//            listener.onAdViewLoadListener();
//        }
    }

    @Override
    public void onRenderFail(NativeExpressADView nativeExpressADView) {
        Log.i(TAG, "onRenderFail: " + nativeExpressADView.getBoundData());
    }

    @Override
    public void onRenderSuccess(NativeExpressADView nativeExpressADView) {
        Log.i(TAG, "onRenderSuccess: ");
        if (listener != null) {
            listener.onAdViewLoadListener();
        }
    }

    @Override
    public void onADExposure(NativeExpressADView nativeExpressADView) {
        Log.i(TAG, "onADExposure: ");
        if (listener != null) {
            listener.onAdViewLoadListener();
        }
    }

    @Override
    public void onADClicked(NativeExpressADView nativeExpressADView) {
        Log.i(TAG, "onADClicked: ");
    }

    @Override
    public void onADClosed(NativeExpressADView nativeExpressADView) {
        Log.i(TAG, "onADClosed: ");
    }

    @Override
    public void onADLeftApplication(NativeExpressADView nativeExpressADView) {
        Log.i(TAG, "onADLeftApplication: ");
    }

    @Override
    public void onADOpenOverlay(NativeExpressADView nativeExpressADView) {
        Log.i(TAG, "onADOpenOverlay: ");
    }

    @Override
    public void onADCloseOverlay(NativeExpressADView nativeExpressADView) {
        Log.i(TAG, "onADCloseOverlay: ");
    }

    @Override
    public void onNoAD(AdError adError) {
        Log.i(
                TAG,
                String.format("onNoAD, error code: %d, error msg: %s", adError.getErrorCode(),
                        adError.getErrorMsg()));
    }

    /**
     * 刷新一下背景模式
     */
    public void setTheme() {
        if (listener != null) {
            listener.onAdViewLoadListener();
        }
    }

    public void onDestory() {
        if (nativeExpressADView != null) {
            nativeExpressADView.destroy();
        }
    }
}